import { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType, Table, TableRow, TableCell, BorderStyle } from 'docx';
import { saveAs } from 'file-saver';
import { WordExportOptions, ExportResult, ExportProgress, DEFAULT_WORD_OPTIONS } from './types';

export class WordExportService {
  private progressCallback?: (progress: ExportProgress) => void;

  constructor(progressCallback?: (progress: ExportProgress) => void) {
    this.progressCallback = progressCallback;
  }

  /**
   * 导出内容为Word文档
   */
  async exportToWord(
    content: string,
    options: Partial<WordExportOptions> = {},
    filename?: string
  ): Promise<ExportResult> {
    try {
      const fullOptions = { ...DEFAULT_WORD_OPTIONS, ...options };
      const finalFilename = filename || this.generateFilename();

      this.reportProgress('preparing', 0, '准备导出内容...');

      // 解析Markdown内容
      const parsedContent = this.parseMarkdown(content);

      this.reportProgress('converting', 25, '转换内容格式...');

      // 创建Word文档
      const doc = this.createWordDocument(parsedContent, fullOptions);

      this.reportProgress('generating', 50, '生成Word文档...');

      // 生成文档缓冲区 - 使用Blob方式以支持浏览器环境
      const blob = await Packer.toBlob(doc);

      this.reportProgress('saving', 75, '保存Word文件...');

      // 保存文件 - 直接使用生成的blob
      saveAs(blob, `${finalFilename}.docx`);

      this.reportProgress('completed', 100, '导出完成');

      return {
        success: true,
        filename: `${finalFilename}.docx`,
        size: blob.size
      };

    } catch (error) {
      console.error('[WordExportService] 导出失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '导出失败'
      };
    }
  }

  /**
   * 解析Markdown内容
   */
  private parseMarkdown(content: string): ParsedElement[] {
    const elements: ParsedElement[] = [];
    const lines = content.split('\n');
    let currentList: string[] = [];
    let inCodeBlock = false;
    let codeBlockContent: string[] = [];
    let codeBlockLanguage = '';

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];

      // 处理代码块
      if (line.startsWith('```')) {
        if (!inCodeBlock) {
          // 开始代码块
          inCodeBlock = true;
          codeBlockLanguage = line.substring(3).trim();
          codeBlockContent = [];
        } else {
          // 结束代码块
          inCodeBlock = false;
          elements.push({
            type: 'codeblock',
            content: codeBlockContent.join('\n'),
            language: codeBlockLanguage
          });
          codeBlockContent = [];
          codeBlockLanguage = '';
        }
        continue;
      }

      if (inCodeBlock) {
        codeBlockContent.push(line);
        continue;
      }

      // 处理列表
      if (line.match(/^[-*+]\s+/)) {
        currentList.push(line.replace(/^[-*+]\s+/, ''));
        continue;
      } else if (currentList.length > 0) {
        elements.push({
          type: 'list',
          items: [...currentList]
        });
        currentList = [];
      }

      // 处理标题
      const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
      if (headingMatch) {
        elements.push({
          type: 'heading',
          level: headingMatch[1].length as 1 | 2 | 3 | 4 | 5 | 6,
          content: headingMatch[2]
        });
        continue;
      }

      // 处理段落
      if (line.trim()) {
        elements.push({
          type: 'paragraph',
          content: line
        });
      } else {
        // 空行
        elements.push({
          type: 'paragraph',
          content: ''
        });
      }
    }

    // 处理剩余的列表
    if (currentList.length > 0) {
      elements.push({
        type: 'list',
        items: currentList
      });
    }

    return elements;
  }

  /**
   * 创建Word文档
   */
  private createWordDocument(elements: ParsedElement[], options: WordExportOptions): Document {
    const children: (Paragraph | Table)[] = [];

    // 添加目录（如果需要）
    if (options.includeTableOfContents) {
      children.push(
        new Paragraph({
          text: '目录',
          heading: HeadingLevel.HEADING_1,
          alignment: AlignmentType.CENTER
        }),
        new Paragraph({ text: '' }) // 空行
      );
    }

    // 处理内容元素
    for (const element of elements) {
      switch (element.type) {
        case 'heading':
          children.push(this.createHeading(element.content, element.level, options));
          break;
        case 'paragraph':
          if (element.content.trim()) {
            children.push(this.createParagraph(element.content, options));
          } else {
            children.push(new Paragraph({ text: '' }));
          }
          break;
        case 'list':
          for (const item of element.items) {
            children.push(this.createListItem(item, options));
          }
          break;
        case 'codeblock':
          children.push(this.createCodeBlock(element.content, options));
          break;
      }
    }

    return new Document({
      sections: [{
        properties: {
          page: {
            margin: {
              top: this.mmToTwips(options.margins.top),
              right: this.mmToTwips(options.margins.right),
              bottom: this.mmToTwips(options.margins.bottom),
              left: this.mmToTwips(options.margins.left)
            }
          }
        },
        headers: options.headerFooter?.header ? {
          default: {
            children: [new Paragraph({ text: options.headerFooter.header })]
          }
        } : undefined,
        footers: options.headerFooter?.footer ? {
          default: {
            children: [new Paragraph({ text: options.headerFooter.footer })]
          }
        } : undefined,
        children
      }],
      creator: '融媒智创工坊',
      title: '导出文档',
      description: '由融媒智创工坊导出的文档'
    });
  }

  /**
   * 创建标题段落
   */
  private createHeading(text: string, level: 1 | 2 | 3 | 4 | 5 | 6, options: WordExportOptions): Paragraph {
    const headingLevels = {
      1: HeadingLevel.HEADING_1,
      2: HeadingLevel.HEADING_2,
      3: HeadingLevel.HEADING_3,
      4: HeadingLevel.HEADING_4,
      5: HeadingLevel.HEADING_5,
      6: HeadingLevel.HEADING_6
    };

    return new Paragraph({
      text: this.parseInlineFormatting(text),
      heading: headingLevels[level],
      spacing: {
        before: 240,
        after: 120
      }
    });
  }

  /**
   * 创建普通段落
   */
  private createParagraph(text: string, options: WordExportOptions): Paragraph {
    return new Paragraph({
      children: this.parseInlineFormatting(text),
      spacing: {
        line: Math.round(options.lineSpacing * 240),
        lineRule: 'auto',
        after: 120
      },
      alignment: AlignmentType.JUSTIFIED
    });
  }

  /**
   * 创建列表项
   */
  private createListItem(text: string, options: WordExportOptions): Paragraph {
    return new Paragraph({
      children: this.parseInlineFormatting(text),
      bullet: {
        level: 0
      },
      spacing: {
        line: Math.round(options.lineSpacing * 240),
        lineRule: 'auto'
      }
    });
  }

  /**
   * 创建代码块
   */
  private createCodeBlock(code: string, options: WordExportOptions): Paragraph {
    return new Paragraph({
      children: [
        new TextRun({
          text: code,
          font: 'Consolas',
          size: Math.round(options.fontSize * 0.9 * 2) // Word使用半点
        })
      ],
      shading: {
        type: 'solid',
        color: 'F8F9FA'
      },
      border: {
        top: { style: BorderStyle.SINGLE, size: 1, color: 'E9ECEF' },
        bottom: { style: BorderStyle.SINGLE, size: 1, color: 'E9ECEF' },
        left: { style: BorderStyle.SINGLE, size: 1, color: 'E9ECEF' },
        right: { style: BorderStyle.SINGLE, size: 1, color: 'E9ECEF' }
      },
      spacing: {
        before: 120,
        after: 120
      }
    });
  }

  /**
   * 解析内联格式（粗体、斜体、链接等）
   */
  private parseInlineFormatting(text: string): TextRun[] {
    const runs: TextRun[] = [];
    let currentText = text;
    let position = 0;

    // 处理粗体 **text**
    const boldRegex = /\*\*(.*?)\*\*/g;
    let lastIndex = 0;
    let match;

    while ((match = boldRegex.exec(text)) !== null) {
      // 添加粗体前的普通文本
      if (match.index > lastIndex) {
        const normalText = text.substring(lastIndex, match.index);
        if (normalText) {
          runs.push(new TextRun({ text: normalText }));
        }
      }

      // 添加粗体文本
      runs.push(new TextRun({
        text: match[1],
        bold: true
      }));

      lastIndex = match.index + match[0].length;
    }

    // 添加剩余的普通文本
    if (lastIndex < text.length) {
      const remainingText = text.substring(lastIndex);
      if (remainingText) {
        runs.push(new TextRun({ text: remainingText }));
      }
    }

    // 如果没有特殊格式，返回普通文本
    if (runs.length === 0) {
      runs.push(new TextRun({ text: text }));
    }

    return runs;
  }

  /**
   * 将毫米转换为Twips（Word单位）
   */
  private mmToTwips(mm: number): number {
    return Math.round(mm * 56.692913386);
  }

  /**
   * 生成文件名
   */
  private generateFilename(): string {
    const now = new Date();
    const timestamp = now.getFullYear() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0') + '_' +
      String(now.getHours()).padStart(2, '0') + 
      String(now.getMinutes()).padStart(2, '0');
    return `文档_${timestamp}`;
  }

  /**
   * 报告导出进度
   */
  private reportProgress(stage: ExportProgress['stage'], progress: number, message: string): void {
    if (this.progressCallback) {
      this.progressCallback({ stage, progress, message });
    }
  }
}

// 解析后的元素类型
interface ParsedElement {
  type: 'heading' | 'paragraph' | 'list' | 'codeblock';
  content?: string;
  level?: 1 | 2 | 3 | 4 | 5 | 6;
  items?: string[];
  language?: string;
}